import { useState, useRef, useEffect } from 'react'
import { Trash2 } from 'lucide-react'
import { Task } from '../types'
import TaskItem from './TaskItem'

interface SwipeableTaskItemProps {
  task: Task
  onToggleComplete: (taskId: string) => void
  onTaskClick: (taskId: string) => void
  onDeleteTask: (taskId: string) => void
  className?: string
}

export default function SwipeableTaskItem({ 
  task, 
  onToggleComplete, 
  onTaskClick, 
  onDeleteTask,
  className = ''
}: SwipeableTaskItemProps) {
  const [translateX, setTranslateX] = useState(0)
  const [isDeleting, setIsDeleting] = useState(false)
  const [showActions, setShowActions] = useState(false)
  const [isSwiping, setIsSwiping] = useState(false)
  
  const containerRef = useRef<HTMLDivElement>(null)
  const startXRef = useRef<number | null>(null)
  const startYRef = useRef<number | null>(null)
  const currentXRef = useRef<number | null>(null)
  
  const SWIPE_THRESHOLD = 80 // 显示操作按钮的阈值
  const MAX_SWIPE_DISTANCE = 120 // 最大滑动距离
  
  // 触摸开始
  const handleTouchStart = (e: React.TouchEvent) => {
    if (isDeleting) return
    
    const touch = e.touches[0]
    startXRef.current = touch.clientX
    startYRef.current = touch.clientY
    currentXRef.current = 0
    setIsSwiping(true)
  }
  
  // 触摸移动
  const handleTouchMove = (e: React.TouchEvent) => {
    if (!startXRef.current || !startYRef.current || isDeleting) return
    
    const touch = e.touches[0]
    const deltaX = touch.clientX - startXRef.current
    const deltaY = touch.clientY - startYRef.current
    
    // 检查是否为水平滑动
    if (Math.abs(deltaX) > Math.abs(deltaY) && Math.abs(deltaX) > 15) {
      // 不调用 preventDefault，避免在被动事件监听器中的问题
      currentXRef.current = deltaX
      
      // 只允许左滑（负方向）
      if (deltaX < 0) {
        const distance = Math.min(Math.abs(deltaX), MAX_SWIPE_DISTANCE)
        setTranslateX(-distance)
      } else {
        setTranslateX(0)
      }
    }
  }
  
  // 触摸结束
  const handleTouchEnd = () => {
    if (!currentXRef.current || isDeleting) {
      resetSwipe()
      return
    }
    
    // 使用当前的实际位移来判断，而不是重新计算
    const currentTranslateX = Math.abs(translateX)
    
    if (currentTranslateX >= SWIPE_THRESHOLD) {
      // 超过显示阈值，显示操作按钮
      setTranslateX(-SWIPE_THRESHOLD)
      setShowActions(true)
    } else {
      // 未超过阈值，回弹
      resetSwipe()
    }
    
    setIsSwiping(false)
  }
  
  // 重置滑动状态
  const resetSwipe = () => {
    setTranslateX(0)
    setShowActions(false)
    setIsSwiping(false)
    startXRef.current = null
    startYRef.current = null
    currentXRef.current = null
  }
  
  // 处理删除
  const handleDelete = async () => {
    if (isDeleting) return
    
    setIsDeleting(true)
    try {
      await onDeleteTask(task.id)
      // 删除成功后，组件会被父组件移除，这里不需要额外处理
    } catch (error) {
      console.error('删除任务失败:', error)
      setIsDeleting(false)
      resetSwipe()
    }
  }
  
  // 点击其他区域时重置
  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
        resetSwipe()
      }
    }
    
    if (showActions) {
      document.addEventListener('mousedown', handleClickOutside)
      return () => document.removeEventListener('mousedown', handleClickOutside)
    }
  }, [showActions])
  
  return (
    <div 
      ref={containerRef}
      className={`relative overflow-hidden rounded-xl ${className}`}
      style={{ touchAction: 'pan-y' }}
    >
                                  {/* 操作按钮区域 */}
       <div 
         className="absolute top-0 right-0 h-full flex items-center justify-center z-10"
         style={{ 
           width: `${SWIPE_THRESHOLD}px`,
           transform: `translateX(${SWIPE_THRESHOLD + translateX}px)`,
           willChange: 'transform'
         }}
       >
         <div className="flex items-center justify-center">
           {/* 删除按钮 */}
           <button
             onClick={handleDelete}
             disabled={isDeleting}
             className="flex flex-col items-center gap-1"
           >
             <div className="w-8 h-8 rounded-full bg-red-500 flex items-center justify-center shadow-sm hover:bg-red-600 transition-colors">
               <Trash2 size={14} className="text-white" />
             </div>
             <span className="text-xs font-medium text-red-700">删除</span>
           </button>
         </div>
       </div>
      
             {/* 任务内容区域 */}
       <div
         className={`relative z-0 transition-transform duration-200 ease-out ${
           isSwiping ? 'transition-none' : ''
         } ${isDeleting ? 'opacity-50' : ''}`}
         style={{ 
           transform: `translateX(${translateX}px)`,
           pointerEvents: isDeleting ? 'none' : 'auto',
           willChange: 'transform'
         }}
         onTouchStart={handleTouchStart}
         onTouchMove={handleTouchMove}
         onTouchEnd={handleTouchEnd}
       >
        <TaskItem
          task={task}
          onToggleComplete={onToggleComplete}
          onClick={() => onTaskClick(task.id)}
        />
      </div>
    </div>
  )
}
